//
//  ViewController.m
//  GuessImage
//
//  Created by 解晓东 on 15/11/18.
//  Copyright (c) 2015年 sasa. All rights reserved.
//

#import "ViewController.h"
#import "SAQuestion.h"

#define kButtonWidth 35
#define kButtonHeight 35
#define kButtonMargin 10
#define kTotalCol 7

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *iconButton;
@property (strong, nonatomic) UIButton *conver;
@property (strong, nonatomic) NSArray *questions;
/** 题目索引 */
@property (assign, nonatomic) int index;
@property (weak, nonatomic) IBOutlet UILabel *noLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *nextQuestionButton;
@property (weak, nonatomic) IBOutlet UIView *answerView;
@property (weak, nonatomic) IBOutlet UIView *optionsView;
@property (weak, nonatomic) IBOutlet UIButton *scoreButton;

@end

@implementation ViewController

- (UIButton *)conver {
    if (_conver == nil) {
        _conver = [[UIButton alloc] initWithFrame:self.view.bounds];
        _conver.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        [self.view addSubview:_conver];
        _conver.alpha = 0.0;
        
        // 监听方法
        [_conver addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventTouchUpInside];

    }
    
    return _conver;
}

- (NSArray *)questions {
    if (_questions == nil) {
         _questions = [SAQuestion questionList];
    }
    
    return _questions;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = -1;
    [self nextQuestion];
}

/** 调整状态栏颜色 */
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 图片切换
/**
 *  chageImage:点击放大/缩小图片
 *
 *  @param sender 按钮本身
 */
- (IBAction)changeImage:(id)sender {
    // 判断按钮是否已经被放大
    if (self.conver.alpha == 0.0) {
        // 2.将图片按钮弄到最前面
        [self.view bringSubviewToFront:self.iconButton]; // 将子视图前置
        
        // 3.动画放大图像按钮
        CGFloat w = self.view.bounds.size.width;
        CGFloat h = w;
        CGFloat y = (self.view.bounds.size.height - h) * 0.5;
        
        [UIView animateWithDuration:1.0f animations:^{
            self.iconButton.frame = CGRectMake(0, y, w, h);
            self.conver.alpha = 1.0;
        }];
    } else {
        // 缩小图片
        [UIView animateWithDuration:1.0 animations:^{
            // 将图像恢复初始位置
            self.iconButton.frame = CGRectMake(85, 102, 150, 150);
            self.conver.alpha = 0.0;
        }];
    }
}

#pragma mark - 下一题
/**
 *  nextQustion：下一题按钮事件
 */
- (IBAction)nextQuestion {
    // 当前答题的索引，索引递增
    ++self.index;
    
    // 如果index已经到最后一题，可以提示用户
    if (self.index == self.questions.count) {
        NSLog(@"答完啦！");
        return ;
    }
    
    // 从数组中按照索引取出题目模型数据
    SAQuestion *question = self.questions[self.index];
    
    // 设置基本信息
    [self setupBasicInfo:question];
    
    // 设置答案按钮
    [self createAnswerButtons:question];
    
    // 创建备选区按钮
    [self createOptionButtons:question];
}

/**
 *  设置基本信息
 *
 *  @param question 数据模型
 */
- (void)setupBasicInfo:(SAQuestion *)question {
    self.noLabel.text = [NSString stringWithFormat:@"%d/%d", self.index + 1, self.questions.count];
    self.titleLabel.text = question.title;
    [self.iconButton setImage:[UIImage imageNamed:question.icon] forState:UIControlStateNormal];
    
    // 如果到达最后一题，就禁用下一题按钮
    self.nextQuestionButton.enabled = (self.index < self.questions.count - 1);
}

/**
 *  创建答案区按钮
 *
 *  @param question 数据模型
 */
- (void)createAnswerButtons:(SAQuestion *)question {
    // 首先清除掉答题区内的所有按钮
    for (UIView *view in self.answerView.subviews) {
        [view removeFromSuperview];
    }
    
    CGFloat answerW = self.answerView.bounds.size.width;
    int length = question.answer.length;
    CGFloat answerX = (answerW - kButtonWidth * length - kButtonMargin * (length - 1)) * 0.5;
    
    // 创建所有答案的按钮
    for (int i = 0; i < length; ++i) {
        CGFloat x = answerX + i * (kButtonMargin + kButtonWidth);
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, kButtonWidth, kButtonHeight)];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn_answer_highlighter"] forState:UIControlStateHighlighted];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [self.answerView addSubview:btn];
        
        [btn addTarget:self action:@selector(answerClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}

/**
 *  创建备选区按钮
 *
 *  @param question 数据模型
 */
- (void)createOptionButtons:(SAQuestion *)question {
    // 避免重新创建
    if (self.optionsView.subviews.count != question.options.count) {
        // 重新创建所有按钮
        // 设置备选按钮
        for (UIView *view in self.optionsView.subviews) {
            [view removeFromSuperview];
        }
        
        CGFloat optionW = self.optionsView.bounds.size.width;
        CGFloat optionX = (optionW - kTotalCol * kButtonWidth - (kTotalCol - 1) * kButtonMargin) * 0.5;
        
        for (int i = 0; i < question.options.count; ++i) {
            int row = i / kTotalCol;
            int col = i % kTotalCol;
            
            CGFloat x = optionX + col * (kButtonMargin + kButtonWidth);
            CGFloat y = row * (kButtonMargin + kButtonHeight);
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(x, y, kButtonWidth, kButtonHeight)];
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_option_highlighter"] forState:UIControlStateHighlighted];
            
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            // 添加按钮监听事件
            [btn addTarget:self action:@selector(optionClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.optionsView addSubview:btn];
        }
    }
    // 如果按钮已经存在，只需要重新设置标题
    int i = 0;
    for (UIButton *btn in self.optionsView.subviews) {
        [btn setTitle:question.options[i++] forState:UIControlStateNormal];
        
        // 恢复
        btn.hidden = NO;
    }
}

#pragma mark - 候选区按钮点击方法
/** 候选按钮点击事件 */
- (void)optionClick:(UIButton *)button {
    // 在答案区找到第一个文字为空得按钮
    UIButton *btn = [self firstAnswerButton];
    
    if (btn == nil) {
        return ;
    }
    
    // 将button的标题设置给答案区的按钮
    [btn setTitle:button.currentTitle forState:UIControlStateNormal];
    
    // 将button隐藏
    button.hidden = YES;
    
    // 判断结果
    [self judge];
}

/** 判断结果 */
- (void)judge {
    BOOL isFull = YES;
    NSMutableString *strM = [NSMutableString string];
    
    // 如果答案区所有按钮都有文字，才判断结果
    // 遍历所有按钮
    for (UIButton *btn in self.answerView.subviews) {
        if (btn.currentTitle.length == 0) {
            isFull = NO;
            break;
        } else {
            // 有字，拼接临时字符串
            [strM appendString:btn.currentTitle];
        }
    }
    
    if (isFull) {
        // 都有字，判断是否和答案一致
        // 根据self.index 获得当前question
        SAQuestion *question = self.questions[self.index];
        // 一致，进入下一题
        if ([strM isEqualToString:question.answer]) {
            // 答对了
            [self setAnswerButtonColor:[UIColor blueColor]]; // 设置颜色
            
            [self changeScore:1000];
            
            // 等待0.5s，进入下一题
            [self performSelector:@selector(nextQuestion) withObject:nil afterDelay:0.5];
        } else {
            // 不一致，提示用户
            [self setAnswerButtonColor:[UIColor redColor]];
        }
        
    } else {
        // 不满
    }
}

/** 修改答题区按钮的颜色 */
- (void)setAnswerButtonColor:(UIColor *)color {
    for (UIButton *btn in self.answerView.subviews) {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
}

/** 在答案区找到第一个文字为空得按钮 */
- (UIButton *)firstAnswerButton {
    // 取按钮标题
    // 遍历答题区所有按钮
    for (UIButton *btn in self.answerView.subviews) {
        if (btn.currentTitle.length == 0) {
            return btn;
        }
    }
    
    return nil;
}

#pragma mark - 答题区按钮点击方法
- (void)answerClick:(UIButton *)button {
    // 如果按钮没有字，直接返回
    if (button.currentTitle.length == 0) {
        return ;
    }
    
    // 如果有字，清除文字，候选区按钮显示
    // 使用按钮的title，去查找候选区域中对应的按钮
    UIButton *btn = [self optionButtonWithTitle:button.currentTitle isHidden:YES];
    btn.hidden = NO;
    [button setTitle:@"" forState:UIControlStateNormal];
    
    // 答题区不完整了
    [self setAnswerButtonColor:[UIColor blackColor]];
}

- (UIButton *)optionButtonWithTitle:(NSString *)title isHidden:(BOOL)isHidden {
    // 遍历候选区域中所有按钮
    for (UIButton *btn in self.optionsView.subviews) {
        // btn.isHidden 为了防止覆盖
        if ([btn.currentTitle isEqualToString:title] && btn.isHidden == isHidden) {
            return btn;
        }
    }
    
    return nil;
}

#pragma mark - 提示功能
- (IBAction)tipClick {
    // 把答题区中所有按钮清空
    for (UIButton *btn in self.answerView.subviews) {
        // 用代码点击答题按钮的操作
        [self answerClick:btn];
    }
    
    // 把正确答案的第一个字，设置到答题区
    // 知道答案的第一个字
    SAQuestion *question = self.questions[self.index];
    NSString *first = [question.answer substringToIndex:1];
    
    UIButton *btn = [self optionButtonWithTitle:first isHidden:NO];
    [self optionClick:btn];
    [self changeScore:-1000];
}

#pragma mark - 分数
- (void)changeScore:(int)score {
    // 取出当前分数
    int currentScroe = self.scoreButton.currentTitle.intValue;
    
    currentScroe += score;
    
    [self.scoreButton setTitle:[NSString stringWithFormat:@"%d", currentScroe] forState:UIControlStateNormal];
}
@end
